package com.speily.current.wait_notify.deathLock;

/**
 * @Auther: SPL
 * @Date: 2019-07-30 14:54
 * @Description: 死锁 - 指两个或者两个以上的线程在执行的过程中，因争夺资源（锁）产生的一种互相等待现象
 */
public class DieLockDemo extends Thread{
    //创建两把锁对象
    public static final Object obj1 = new Object();
    public static final Object obj2 = new Object();
    private boolean flag = false;
    public DieLockDemo(String name ,boolean flag) {
        super(name);
        this.flag = flag;
    }

    @Override
    public void run() {
        while(true){
            if(flag){
                synchronized (obj1) {
                    System.out.println(getName()+" use obj1");
                    synchronized (obj2) {
                        System.out.println(getName()+" use obj2");
                        obj2.notify();
                    }
                    try {
                        obj1.wait();//释放obj1锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                synchronized (obj2) {
                    System.out.println(getName()+" use obj2");

                    synchronized (obj1) {
                        System.out.println(getName()+" use obj1");
                        obj1.notify();
                    }
                    try {
                        obj2.wait();//释放obj2锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {

        //无限执行，因为锁竞争wait
        DieLockDemo d1 = new DieLockDemo("小王", true);
        DieLockDemo d2 = new DieLockDemo("小强", false);
        d1.start();
//        Thread.sleep(1000l);
        d2.start();


        //解决，


    }
}
